const WXAPI = require('../../wxapi/main')
const con = require("../../utils/data.js");
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    bindGetUserInfo: function(e) {
        if (!e.detail.userInfo) {
            return;
        }
        if (app.globalData.isConnected) {
            wx.setStorageSync('userInfo', e.detail.userInfo)
            this.login();
        } else {
            wx.showToast({
                title: '当前无网络',
                icon: 'none',
            })
        }
    },
    login: function() {
        const that = this;
        const token = wx.getStorageSync('token');
        if (token) {
            WXAPI.checkToken(token).then(function(res) {
                if (res.code != 0) {
                    wx.removeStorageSync('token')
                    that.login();
                } else {
                    // 回到原来的地方放
                    app.navigateToLogin = false
                    wx.navigateBack();
                }
            })
            return;
        }
        wx.login({
            success: function(res) {
                WXAPI.login(res.code).then(function(res) {
                    if (res.code == 10000) {
                        // 去注册
                        that.registerUser();
                        return;
                    }
                    
                    wx.setStorageSync('token', res.data.token)
                    wx.setStorageSync('uid', res.data.uid)
                        // 回到原来的地方放
                    app.navigateToLogin = false
                    wx.navigateBack();
                })
                that.getOpenId()
            }
        })
    },
    //用code请求openid
    getOpenId: function() {
        wx.login({
                success: function(res) {
                    var code = res.code; //返回code
                    // console.log(code);
                    var appId = 'wxfc765da9b36bb1a4';
                    var secret = 'bac797d8d10a5d9054ad73e7d27b9fbb';
                    wx.request({
                        // url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appId + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code',
                        url:'https://www.brvpmusic.com/wechat/getOpenId',
                        data: {
                                'code': code
                              },
                        method: 'GET',
                        header: {
                            'content-type': 'json'
                        },
                        success: function(res) {
                            var userInfo = wx.getStorageSync('userInfo');
                            var openid = res.data.openid; //返回openid
                            var session_key = res.data.session_key; //返回session_key
                                // 存用户信息到全局变量
                            var app = getApp();
                            app.globalData.session_key = session_key;
                            if(openid!=''&&openid!='undefined'){
                                app.globalData.openid = openid;
                                wx.setStorageSync('OpenId', openid);
                            }else{
                                app.globalData.openid = '';
                                wx.setStorageSync('OpenId', '');
                            }
                            console.log('返回成功');
                            console.log(userInfo.nickName);
                            console.log('返回openid---'+openid);
                            console.log(userInfo.avatarUrl);
                            console.log("结果-----" + wx.getStorageSync('upper_fSid'));
                            // 触发注册openid
                            wx.request({
                                url: con.index_slogin,
                                method: 'GET',
                                header: {
                                    'content-type': 'application/json'
                                },
                                data: {
                                    'openid': app.globalData.openid,
                                    'nickname': userInfo.nickName,
                                    'cHeadimgurl': userInfo.avatarUrl,
                                    'fSid': wx.getStorageSync('upper_fSid')
                                },
                                success: function(res) {
                                    console.log('openid，昵称，头像传输成功');
                                    console.log(res.data);
                                    wx.navigateTo({
                                        url: "/pages/authorize/bindmobile"
                                    })
                                },
                                fail: function(res) {
                                    console.log('openid，昵称，头像传输失败')
                                }
                            })
                        }
                    })
                }
            })
    },
    registerUser: function() {
        let that = this;
        wx.login({
            success: function(res) {
                let code = res.code; // 微信登录接口返回的 code 参数，下面注册接口需要用到
                wx.getUserInfo({
                    success: function(res) {
                        let iv = res.iv;
                        let encryptedData = res.encryptedData;
                        let referrer = '' // 推荐人
                        let referrer_storge = wx.getStorageSync('referrer');
                        if (referrer_storge) {
                            referrer = referrer_storge;
                        }
                        // 下面开始调用注册接口
                        WXAPI.register({
                            code: code,
                            encryptedData: encryptedData,
                            iv: iv,
                            referrer: referrer
                        }).then(function(res) {
                            wx.hideLoading();
                            that.login();
                        })
                    }
                })
            }
        })
    },
    goIndex() {
        wx.reLaunch({
            url: "/pages/index/index"
        })
    }
})